const http = require('http');
const qs = require('querystringify');

const { httpWriteParse, read, learnShenTong, learnGongFa, pathc } = require("./util")

// 角色属性
// let juexeXinXI = JSON.parse(read(path.juese));
let shentongXinXI = JSON.parse(read(pathc.shentong));
let gongfaXinXI = JSON.parse(read(pathc.gongfa));

// 角色信息解析

function jsons(data) {
    let juexeXinXI = JSON.parse(data);
    return {
        jueseData:{
            name: juexeXinXI.name,
            age: juexeXinXI.age,
            shouyuan: juexeXinXI.shouYuan,
            level: juexeXinXI.level,
            menPai: juexeXinXI.menPai,
            ZiZhi: juexeXinXI.ZiZhi,
            wuXin: juexeXinXI.wuXin,
            _dunSu: juexeXinXI._dunSu,
            _shengShi: juexeXinXI._shengShi,
            exp: juexeXinXI.exp,
            HP: juexeXinXI.HP,
            _HP_Max: juexeXinXI._HP_Max,
            money: juexeXinXI.money,
            Dandu: juexeXinXI.Dandu,
            _WuDaoDian: juexeXinXI._WuDaoDian,
            hasStaticSkillList: juexeXinXI.hasStaticSkillList,
            hasSkillList: juexeXinXI.hasSkillList,
            itemList: juexeXinXI.itemList
                
        }
    }
}


// 接口请求路径及内容
let GETrouter = [
    {
        path: '/getjs',
        data: jsons(read(pathc.juese)).jueseData
    },
    {
        path: '/getst',
        data: shentongXinXI
    },
    {
        path: '/getgf',
        data: gongfaXinXI
    }
]

let studyRouter = [
    {
        path:"/lnst",
        funs: learnShenTong
    },
    {
        path: "/lngf",
        funs: learnGongFa
    }
]

// 参数命中状态
let stust = false;

// 实现server
let Server = http.createServer((req, res)=> {
    res.writeHead(200, { 'Content-Type': 'text/plain;charset=utf-8', "Access-Control-Allow-Origin": "*" });
    
    if (req.method == "GET"){
        // 更新暴露信息
        if (req.url == "getjs") GETrouter[0].data = jsons(read(path.juese)).jueseData;

        // 信息读取
        for (let i in GETrouter) {
            if (GETrouter[i].path == req.url) {
                res.write(httpWriteParse(GETrouter[i].data));
                stust = true;
                break;
            }
        }

        // console.log(11111)
        // 信息写入
        if (!stust) res.write(`{"data":{"msg":"请检查请求参数是否正确！"},"status":"404"}`);
        res.end();
    }

    req.on('data', (parmas) => {
        let { data } = qs.parse(parmas);

        for (let i in studyRouter) {
            if (studyRouter[i].path == req.url) {
                studyRouter[i].funs(parseInt(data));
                res.write(`{"data":{"msg":"学习成功！"},"status":"200"}`);
                stust = true;
                break;
            }

        }
        // 信息写入
        if (!stust) res.write(`{"data":{"msg":"请检查请求参数是否正确！"},"status":"404"}`);
        res.end();
    })
})


module.exports = {
    Server
}